package tech.yunland.shop.domain.dao;

import com.moyuer.bsf.domain.dao.BaseDao;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by yunland03 on 16-11-17.
 */
@Repository
public class ShipUserDao extends BaseDao<String,String> {

    public int saveShipOrganToUser(String organId,String openId){

        Session session = this.getSession();

        String sqlCount = "select count(1) from wx_user_organ where organ_id='"+organId+"'  and openid='"+openId+"'";

        SQLQuery sqlCountQuery = session.createSQLQuery(sqlCount);
        Object ocount = sqlCountQuery.uniqueResult();

        BigInteger bcount = (BigInteger) ocount;
       int count =  bcount.intValue();
        int flag = 0;
        if(count==0){
            String sql = "INSERT into wx_user_organ (organ_id,openid) VALUES ('"+organId+"','"+openId+"')";
            SQLQuery sqlQuery =  session.createSQLQuery(sql);
            flag =  sqlQuery.executeUpdate();
        }



        return flag;



    }

    public Boolean breakShipUserToPlant(String oid, String openId) {
        int flag = 0;
        Session session = this.getSession();
        String sql = "delete from wx_user_organ where organ_id='"+oid+"'  and openid='"+openId+"'";
        SQLQuery sqlQuery =  session.createSQLQuery(sql);
        flag = sqlQuery.executeUpdate();
        if(flag>=0){
            return true;
        }

        return false;



    }

    public List<String> getOpenIdsByOrganId(String organId) {
        String sql = "select openid from wx_user_organ where organ_id= '"+organId+"' ";
        List<Map<String,Object>> list = this.findBySQL(sql,new Object[]{});
        List<String> openIds = new ArrayList<>();
        if(list!=null) {
            for (Map<String, Object> openIdMap : list) {
                        String openId = (String)openIdMap.get("openid");
                        if(StringUtils.isNoneBlank(openId)){
                                openIds.add(openId);
                        }
            }

        }
        return openIds;

    }
}
